import { NumberPanelService } from './../../../component/primeng/numberpanel/numberpanel.service';
import { NavigateService } from './../../../service/navigate.service';
import { MdDialog, MdDialogRef, MdDialogConfig, MdSnackBar } from "@angular/material";
import { MessageBoxService, GrowlMessageType } from './../../../component/messageBoxService';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

export class InvtAmountService {
    static Current: InvtAmountService = new InvtAmountService();
    private invtTemp: InvtAmountDialog;
    dialogRef: MdDialogRef<InvtAmountDialog>;
    config: MdDialogConfig = {
        disableClose: false,
        width: '100%',
        position: {
            top: '',
            bottom: '0',
            left: '',
            right: ''
        }
    }

    Regist(invtTemp: InvtAmountDialog) {
        this.invtTemp = invtTemp;
    }

    /**
     * @param  {string} type   dialog类型  "refund"(退菜)|"serve"(上菜)
     * @param  {string} title  dialog的title "退"|"上"
     * @param  {string} name   菜品名
     * @param  {number} invtQty  菜品总数量
     * @param  {number} dished   已上菜数量
     */
    open(dialog: MdDialog, type: string, title: string, invtQty: number, dished: number, refunded: number, refundReason, unitType?: string) {
        this.dialogRef = dialog.open(InvtAmountDialog, this.config);
        refunded = parseFloat(refunded + "");
        this.invtTemp.title = title;
        this.invtTemp.invtQty = invtQty;
        this.invtTemp.type = type;
        this.invtTemp.dished = dished;
        this.invtTemp.refundReason = refundReason;
        if (type == 'refund') {
            this.invtTemp.qty = invtQty - refunded;
        } else if (type = 'serve') {
            this.invtTemp.qty = invtQty - dished - refunded;
        }
        this.invtTemp.unitType = unitType;
        if (unitType) {
            this.invtTemp.operateQty = this.invtTemp.qty;
            this.invtTemp.weight = parseFloat(this.invtTemp.qty + "");
        } else {
            this.invtTemp.operateQty = 1;
        }
        this.invtTemp.refundQty = refunded;
        return new Promise<any>((resolve, reject) => {
            this.dialogRef.afterClosed().subscribe((msg) => {
                this.dialogRef = null;
                resolve(msg);
            });
        });
    }

}

@Component({
    //moduleId: module.id,
    selector: 'div[invt-amount]',
    template: `
        <md-dialog-content fxLayout="column">
            <div tabindex="0" autofocus fxLayout="row" fxLayoutAlign="start center" class="invt-amount-title noshrink">
                <span class="margin-l-s" fxFlex="100%">本次{{type=="refund"?"退菜":"上菜"}}数量</span>
                <span id="dialog-back-btn" class="i-clear noshrink margin-r-s" (click)="cancel()"></span>
            </div>
            <div *ngIf="type == 'refund'" fxLayout="row" fxLayoutWrap="wrap" class="refund-container v-gap v-scroll padding-s noshrink">
                <div *ngFor="let reason of refundReason" class="tag" (click)="chooseRefundReason(reason)">
                    <span>{{reason.content}}</span>
                </div>
                <textarea class="refund-reason pct100 text-xs padding-xs color-lightgray" placeholder="请输入退菜理由" [(ngModel)]="reasonText"></textarea>
            </div>
            <div fxLayout="column" fxLayoutAlign="center start" class="invt-amount-info">
                <div class="pct100" *ngIf="qty > 0">
                    <div fxLayout="row" fxLayoutAlign="center center" class="text-s" *ngIf="!unitType">
                        <span fxFlex="100%" *ngIf="type=='refund'" class="margin-l-s">可退{{invtQty - refundQty}}份</span>
                        <span fxFlex="100%" *ngIf="type=='serve'" class="margin-l-s">已上{{dished}}份，还需上{{invtQty - dished - refundQty}}份</span>
                        <div class="noshrink" fxLayout="row" fxLayoutAlign="start center">
                            <div class="icon-minus-circle-o invt-amount-minus margin-l-s" (click)="onInvtMinus(operateQty)"></div>
                            <div fxLayout="row" fxLayoutAlign="center center" class="invt-amount-qty margin-l-s" (click)="changeQty()">{{operateQty}}</div>
                            <div class="i-add-circle invt-amount-add margin-l-s color-primary" (click)="onInvtAdd(operateQty)"></div>
                        </div>
                    </div>
                    <div fxLayout="row" fxLayoutAlign="center center" *ngIf="unitType=='weight'">
                        <md-input-container>
                            <input mdInput [(ngModel)]="weight">
                        </md-input-container>
                    </div>
                </div>
                <div class="text-s margin-l-s" *ngIf="qty <= 0">
                    <span>菜品已上齐</span>
                </div>
            </div>
            <button md-button class="bgcolor-accent color-white noshrink normal-btn text-m pct100" (click)="ok()">确定</button>
        </md-dialog-content>
    `,
    styleUrls: ['../tableDetail.component.scss']
})
export class InvtAmountDialog implements OnInit {

    constructor(
        private msgSvr: MessageBoxService,
        public dialogRef: MdDialogRef<InvtAmountDialog>,
        public snackBar: MdSnackBar,
        private navSvr: NavigateService,
        private dialog: MdDialog
    ) {
        InvtAmountService.Current.Regist(this);
    }

    refundObj = <any>{};
    ngOnInit() {
        this.navSvr.registGoBack(() => {
            let btn = document.getElementById("dialog-back-btn");
            if (btn) {
                btn.click();
            }
        });
    }

    title: string

    invtQty: number;   //总数量

    type: string;

    dished: number; //已上菜的数量

    onInvtResult = new EventEmitter();

    qty: number;   //操作后的数量

    refundQty: number; //退菜数量

    unitType: string; //单位类型

    weight: number;  //称重商品的重量

    snackBarRef = null;

    operateQty: number;

    refundReason;
    reasonText: string = ""
    /**
     * 减少商品
     */
    onInvtMinus(operateQty) {
        if (this.operateQty > 1) {
            this.operateQty--;
            return;
        }
        if (!this.snackBarRef) {
            this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "数量不能小于1");
            this.snackBarRef.afterDismissed().subscribe(() => {
                this.snackBarRef = null;
            });
        }

        this.operateQty = 1;
    }
    /**
     * 添加商品
     */
    onInvtAdd(operateQty, num?: Number) {
        if (num != undefined && (!Number(num) || Number(num) == 0)) {
            this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "数量不能小于1");
            return;
        }
        let maxNum = 0;
        if (this.type == 'refund') {
            maxNum = this.invtQty - this.refundQty;
            if (this.operateQty <= maxNum) {
                if (num) {
                    if (Number(num) <= this.invtQty - this.refundQty) {
                        this.operateQty = Number(num);
                    } else {
                        this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "数量大于了你的商品数");
                    }
                } else {
                    if (this.operateQty == maxNum) {
                        this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "数量大于了你的商品数");
                    } else {
                        this.operateQty++;
                    }
                }
                return;
            }
        } else if (this.type == 'serve') {
            maxNum = this.invtQty - this.dished - this.refundQty;
            if (this.operateQty < maxNum) {
                if (num) {
                    if (Number(num) <= this.invtQty - this.dished - this.refundQty) {
                        this.operateQty = Number(num);
                    } else {
                        this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "数量大于了你的商品数");
                    }
                } else {
                    this.operateQty++;
                }
                return;
            }
        }
        if (!num) {
            if (!this.snackBarRef) {
                this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "数量大于了你的商品数");
                this.snackBarRef.afterDismissed().subscribe(() => {
                    this.snackBarRef = null;
                });
            }
        } else {
            if (Number(num) && Number(num) > maxNum) {
                this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "数量大于了你的商品数");
            }
        }
    }
    /**
     * 选择退菜理由
     * @param reason 退菜理由
     */
    chooseRefundReason(reason) {
        if (this.reasonText) {
            this.reasonText += ("," + reason.content);
        } else {
            this.reasonText = reason.content;
        }
    }
    /**
     * 修改数量
     */
    async changeQty() {
        let initQty = this.operateQty + "";
        let isDecimal = this.unitType == 'weight';
        let result: any = await NumberPanelService.current.open(this.dialog, "修改数量", null, initQty, isDecimal);
        if (result != undefined) {
            this.onInvtAdd(this.operateQty, result);
        }
    }
    /**
     * 关闭对话框，不做操作
     */
    cancel() {
        this.dialogRef.close("");
    }
    /**
     * 取消上菜
     */
    cancelServed() {
        this.dialogRef.close("cancel");
    }
    /**
     * 关闭对话框，确认操作
     */
    ok() {
        var regexp = new RegExp(/^\d+(\.\d+)?$/)

        if (this.type == 'serve' && this.qty <= 0) {
            if (!this.snackBarRef) {
                this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "菜品已上齐");
                this.snackBarRef.afterDismissed().subscribe(() => {
                    this.snackBarRef = null;
                });
            }
            return;
        }
        if (this.unitType && this.unitType == 'weight') {
            if (this.weight <= 0) {
                if (!this.snackBarRef) {
                    this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "重量不能小于0");
                    this.snackBarRef.afterDismissed().subscribe(() => {
                        this.snackBarRef = null;
                    });
                }
                return;
            } else if (this.weight > Number(this.qty)) {
                if (!this.snackBarRef) {
                    this.snackBarRef = this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "重量超过现有的重量");
                    this.snackBarRef.afterDismissed().subscribe(() => {
                        this.snackBarRef = null;
                    });
                }
                return;
            }
            if (!regexp.test(this.weight + "")) {
                this.msgSvr.Growl(GrowlMessageType.Warning, this.snackBar, "请输入数字重量，如[8.88]斤");
                return;
            }
            this.weight = parseFloat(this.weight + "");
            this.refundObj.value = this.weight;
            this.refundObj.refundReason = this.reasonText;
            if (this.type == 'serve') {
                this.dialogRef.close(this.refundObj.value);
            } else {
                this.dialogRef.close(this.refundObj);
            }
        } else {
            this.refundObj.value = this.operateQty;
            this.refundObj.refundReason = this.reasonText;
            if (this.type == 'serve') {
                this.dialogRef.close(this.refundObj.value);
            } else {
                this.dialogRef.close(this.refundObj);
            }
        }
    }
}